import isValid from "../_util/isValid"
import { ExpandTransitionProps } from "./expand-transition"

function get(num: number | Function, origin: number): string {
  let size = typeof num === 'function' ? num(origin) : num
  return size + 'px'
}

export default function (props: ExpandTransitionProps) {
  return {
    onEnter: (el: HTMLElement) => {
      el.style.transition = `none`
      el.style[props.heightProp] = ''
      el.style[props.widthProp] = ''
      
      const height = el.offsetHeight, width = el.offsetWidth
      
      if (isValid(props.height)) el.style[props.heightProp] = get(props.height, height)
      if (isValid(props.width)) el.style[props.widthProp] = get(props.width, width)
      void el.offsetWidth
      
      el.style.transition = ``
      if (isValid(props.height)) el.style[props.heightProp] = `${height}px`
      if (isValid(props.width)) el.style[props.widthProp] = `${width}px`
      void el.offsetWidth
    },

    onAfterEnter: (el: HTMLElement) => {
      el.style[props.heightProp] = ``
      el.style[props.widthProp] = ``
    },

    onBeforeLeave: (el: HTMLElement) => {
      if (isValid(props.height)) el.style[props.heightProp] = `${el.offsetHeight}px`
      if (isValid(props.width)) el.style[props.widthProp] = `${el.offsetWidth}px`
      void el.offsetWidth
    },

    onLeave: (el: HTMLElement) => {
      const height = el.offsetHeight, width = el.offsetWidth
      if (isValid(props.height)) el.style[props.heightProp] = get(props.height, height)
      if (isValid(props.width)) el.style[props.widthProp] = get(props.width, width)
      void el.offsetWidth
    },

    onAfterLeave: (el: HTMLElement) => {
      el.style[props.heightProp] = ``
      el.style[props.widthProp] = ``
    }
  }
}